import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: '/api/v1',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    // 添加请求时间戳
    config.metadata = { startTime: new Date() }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    // 计算请求耗时
    const endTime = new Date()
    const duration = endTime - response.config.metadata.startTime
    response.duration = duration
    return response
  },
  error => {
    console.error('API请求失败:', error)
    return Promise.reject(error)
  }
)

/**
 * KV服务API
 */
export const kvService = {
  
  /**
   * 获取或创建KV对
   */
  async getOrCreate(key, defaultValue = null) {
    if (defaultValue) {
      const response = await api.post('/kv/get-or-create', {
        key,
        value: defaultValue
      })
      return response.data
    } else {
      const response = await api.get(`/kv/${encodeURIComponent(key)}`)
      return response.data
    }
  },

  /**
   * 更新KV对
   */
  async update(key, value) {
    const response = await api.put(`/kv/${encodeURIComponent(key)}`, {
      key,
      value
    })
    return response.data
  },

  /**
   * 删除KV对
   */
  async delete(key) {
    const response = await api.delete(`/kv/${encodeURIComponent(key)}`)
    return response.status === 200
  },

  /**
   * 批量获取或创建
   */
  async batchGetOrCreate(keys) {
    const response = await api.post('/kv/batch/get-or-create', {
      items: keys
    })
    return response.data
  },

  /**
   * 异步批量获取或创建
   */
  async batchGetOrCreateAsync(keys) {
    const response = await api.post('/kv/batch/get-or-create-async', {
      items: keys
    })
    return response.data
  },

  /**
   * 获取热点数据
   */
  async getHotKeys(limit = 10) {
    const response = await api.get(`/kv/hot-keys?limit=${limit}`)
    return response.data
  },

  /**
   * 缓存预热
   */
  async warmUpCache(keys) {
    const response = await api.post('/kv/cache/warm-up', keys)
    return response.data
  },

  /**
   * 清理缓存
   */
  async clearCache() {
    const response = await api.delete('/kv/cache/clear')
    return response.data
  },

  /**
   * 获取统计信息
   */
  async getStatistics() {
    const response = await api.get('/kv/stats')
    return response.data
  },

  /**
   * 健康检查
   */
  async healthCheck() {
    const response = await api.get('/kv/health')
    return response.data
  },

  /**
   * 按值分组统计访问次数
   */
  async groupByValue(pattern) {
    const response = await api.get('/kv/group-by/value', {
      params: { pattern }
    })
    return response.data
  },

  /**
   * 按日期分组统计访问次数
   */
  async groupByDate(startDate, endDate) {
    const response = await api.get('/kv/group-by/date', {
      params: { startDate, endDate }
    })
    return response.data
  },

  /**
   * 按日期和值分组统计访问次数
   */
  async groupByDateAndValue(pattern, startDate, endDate) {
    const response = await api.get('/kv/group-by/date-value', {
      params: { pattern, startDate, endDate }
    })
    return response.data
  },

  /**
   * 查找包含特定值的记录
   */
  async searchByValue(pattern) {
    const response = await api.get('/kv/search/value', {
      params: { pattern }
    })
    return response.data
  }
}

export default kvService